<?php
/*
 * @Description    : 添加IP到黑名单
 * @Version        : 1.0.0
 * @Author         : QianLong
 * @Date           : 2020-02-18 18:11:17
 * @LastEditors    : QianLong
 * @LastEditTime   : 2023-11-18 10:25:41
 */

declare(strict_types=1);

namespace App\Job;

use Hyperf\AsyncQueue\Job;
use App\Common\RedisCache;
use Yurun\Util\HttpRequest;

class AddIpBlackJob extends Job
{
	public $params;

	public function __construct($params)
	{
		$this->params = $params;
	}

	public function handle()
	{
		$paramters = $this->params;
		$self = $this;
		\Hyperf\Retry\Retry::whenReturns(false) // 当返回false时重试
			->max(3) // 最多3次
			->inSeconds(3 * 60) // 最长5秒
			->sleep(1000 * 5) // 间隔1毫秒
			->fallback(function () use ($paramters, $self) {
				$result = $self->doRequest($paramters);
				if ($result) {
					return true;
				}
				return false;
			}) // fallback函数
			->call(function () use ($paramters, $self) {
				$result = $self->doRequest($paramters);
				if ($result) {
					return true;
				}
				return false;
			});
	}
	private function doRequest($params)
	{
		$redisCache = new RedisCache();
		redis()->set('openmqt_' . $params['ip'] . '_REFUSE', 1);
		$ipinfo = $redisCache->getIpInfoRealTime($params['ip']);
		$params['reason'] = (isset($params['reason'])) ? $params['reason'] : '频繁超出会员等级频率限制';
		$updateData['isblack'] = 1;
		$updateData['black_reason'] = $params['reason'];
		$updateData['add_black_time'] = (int)time();
		$searchCondition['_id'] = $params['ip'];
		mongodb2()->ip_white_list->updateOne($searchCondition, ['$set' => $updateData]);
		if ($params['email']) {
			$msg = '尊敬的 ' . $ipinfo['username'] . '，您的IP：' . $params['ip'] . ' 因' . $params['reason'] . '，已被系统判定为恶意调用并将此IP列为访问黑名单，可登录会员中心后，在IP白名单处进行处理，或下载使用“喵有券”APP进行处理，如有疑问，请联系：87989431或87498106，感谢您的支持！';
			$emailSendData['title'] = 'IP处罚通知';
			$emailSendData['email'] = $params['email'];
			$emailSendData['content'] = $msg;
			$emailSendData['et_id'] = 'ET4644661467997738';
			queue_push(new SendEmailJob($emailSendData));
		}
		$logdata['title'] = 'IP黑名单';
		$logdata['uid'] = 0;
		$logdata['username'] = $ipinfo['username'];
		$logdata['is_admin'] = 1;
		$logdata['extlog'] = '添加IP黑名单，IP：' . $params['ip'] . '，原因：' . $params['reason'] . '，所属用户：' . $ipinfo['username'];
		queue_push(new OperateLogAddJob($emailSendData));
		return true;
	}
}
